import store from "@/store";
import { getUserChatList } from "@/axios/community.js";
export default class WebSocketTool {
  constructor(url) {
    this.url = url;
    this.ws = null;
  }

  connect(data) {
    if (!this.ws) {
      this.ws = new WebSocket(this.url);
      this.ws.onopen = () => {
        if (this.isReconnecting) return;
        let sendData = JSON.stringify(data);
        this.ws.send(sendData); // 连接成功立即发送数据
      };

      this.ws.onclose = () => {
        this.ws = null;
        // console.log("WebSocket断开");
        this.reconnect();
      };

      this.ws.onmessage = (msg) => {
        let message = JSON.parse(msg.data);
        // console.log(message.tip); 
        if (message.tip == "bind_success") {
          // console.log("WebSocket连接成功");
          this.getUserChatLists();
          this.startheader();
          clearInterval(this.time)
          this.isReconnecting = true;
        } else if (message.tip == "heart") {
          // console.log("WebSocket监听中");
        } else if (message.mode == 5) {
          // console.log("来消息了");
          this.getUserChatLists();
          store.commit("setwebsoketnums", 1);
        } else {
          this.ws.close();
        }
        // switch (message.tip) {
        //   case "bind_success":

        //     break;
        //   default:
        //     this.ws.close();
        //     break;
        // }
      };
    }
    return this.ws;
  }

  send(msg) {
    if (this.ws) {
      this.ws.send(msg);
    }
  }
  startheader() {
    console.log("jir");
    this.time = setInterval(() => {
      let datas = {};
      datas.device = "mp";
      datas.mode = "bind";

      datas.played = "";
      datas.token = store.state.minToken;
      this.ws.send(JSON.stringify(datas)); // 连接成功立即发送数据
    }, 10000);
  }
  reconnect() {
    // 加锁,防止重复重连
    if (this.isReconnecting) return;
    this.isReconnecting = true;
    if (!this.reconnectInterval) {
      this.reconnectInterval = setInterval(() => {
        this.connect();
        this.isReconnecting = false;
        clearInterval(this.reconnectInterval);
        this.reconnectInterval = null;
      }, 2000); // 每2秒重连一次
    }
    // if (!this.ws) {
    //   this.connect();
    // }
  }
  close() {
    if (this.ws) {
      this.ws.close();
    }
  }
  // 消息列表
  getUserChatLists = () => {
    getUserChatList().then((res) => {
      let xiaoxiNum = 0;
      res.data.forEach((item, index) => {
        xiaoxiNum += Number(item.read_count);
      });
      store.commit("setxiaoxiNum", xiaoxiNum);
      store.commit("setPersonlist", res.data);
    });
  };
}
